package com.edu.app.controller;

import com.edu.app.constant.ErrorConstant;
import com.edu.app.exception.BaseException;
import com.edu.app.util.ErrorUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by xiongjian on 2018/10/24.
 * 全局异常处理，捕获所有Controller中抛出的异常。
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //处理自定义的异常
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public Object customHandler(BaseException e){
        logger.error(e.getMessage());
        return ErrorUtil.retErrMsg(e.getCode());

    }
    //其他未处理的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exceptionHandler(Exception e){
        logger.error( e.getStackTrace().toString());
        return ErrorUtil.retErrMsg(ErrorConstant.SERVER_INTERNAL_ERROR);
    }
}
